package cn.ucuser.music.utils;

import com.google.gson.Gson;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.HashMap;
import java.util.Map;

public class AES {
    private final static String MODULUS = "00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3e82047b97ddef52741d546b8e289dc6935b3ece0462db0a22b8e7";
    private final static String NONCE = "0CoJUm6Qyw8W8jud";
    private final static String PUBKEY = "010001";
    private final static String secretKey = "TA3YiYCfY2dDJQgg";
    private final static String encSecKey = "84ca47bca10bad09a6b04c5c927ef077d9b9f1e37098aa3eac6ea70eb59df0aa28b691b7e75e4f1f9831754919ea784c8f74fbfadf2898b0be17849fd656060162857830e241aba44991601f137624094c114ea8d17bce815b0cd4e5b8e2fbaba978c6d1d14dc3d1faf852bdd28818031ccdaaa13a6018e1024e2aae98844210";
    private final static String VI = "0102030405060708";


    public static Map<String, Object> getPrepare(Map<String, Object> raw) {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("params", encrypt(jsonEncode(raw), NONCE));
        data.put("params", encrypt((String) data.get("params"), secretKey));
        data.put("encSecKey", encSecKey);
        return data;
    }

    public static String jsonEncode(Object object) {
        return new Gson().toJson(object);
    }

    private static String encrypt(String content, String password) {
        try {
            SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
            IvParameterSpec iv = new IvParameterSpec(VI.getBytes());// 创建iv
            byte[] byteContent = content.getBytes("utf-8");
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);// 初始化
            byte[] result = cipher.doFinal(byteContent);
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(result); // 加密
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
